package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.example.blue.ui.DynamicWaveFormView;

import org.example.result.FeaResult;

import java.util.concurrent.ConcurrentLinkedQueue;


public class DuizhiActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "DuizhiActivity";
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound=false;
    private Button btn;
    private Boolean startFlag=false;
    private Integer handDir;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private Thread workerThreadx;
    private Thread workerThready;
    private Thread workerThreadz;
    private Boolean runningx=false;
    private Boolean runningy=false;
    private Boolean runningz=false;
    private LinearLayout groupLayout;
    private ImageView imageView;
    private TextView shuomingText;
    private DataProcessorManager processorManager;
    private final ConcurrentLinkedQueue<Float> magxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magzDataQueue = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(DuizhiActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(bluetoothService.getDataQueue());
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duizhi);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("对指测试");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        handDir = sp.getInt("handDir",1);
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(DuizhiActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }

        imageView=findViewById(R.id.imageView);
        shuomingText=findViewById(R.id.shuoming);
        groupLayout=findViewById(R.id.group_container);

        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("Z轴欧拉角(deg)");
        waveformViewX.setYRange(-180,180);
        waveformViewY.setYtitle("Y轴欧拉角(deg)");
        waveformViewY.setYRange(-180,180);
        waveformViewZ.setYtitle("X轴欧拉角(deg)");
        waveformViewZ.setYRange(-180,180);
        if(startFlag==false){
            groupLayout.setVisibility(View.GONE);
        }else{
            groupLayout.setVisibility(View.VISIBLE);
        }

        btn = findViewById(R.id.startBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(DuizhiActivity.this);
//                builder.setTitle("请选择")
//                        .setItems(new String[]{"左手", "右手"}, (dialog, which) -> {
//                            if (which == 0) {
                                groupLayout.setVisibility(View.VISIBLE);
                                imageView.setVisibility(View.GONE);
                                shuomingText.setVisibility(View.GONE);
                                btn.setVisibility(View.GONE);

                                waveformViewX.clearDataPoints();
                                waveformViewY.clearDataPoints();
                                waveformViewZ.clearDataPoints();

                                processorManager.setDeviceMac(deviceId.replace(":",""));
                                processorManager.temp=handDir;
                                processorManager.setDataUpdateListener(DuizhiActivity.this);
                                processorManager.startProcessing();
                                processorManager.setProcessingFunction(ProcessingFunction.Duizhiout);
//                            } else {
//                                groupLayout.setVisibility(View.VISIBLE);
//                                imageView.setVisibility(View.GONE);
//                                shuomingText.setVisibility(View.GONE);
//                                btn.setVisibility(View.GONE);
//
//                                waveformViewX.clearDataPoints();
//                                waveformViewY.clearDataPoints();
//                                waveformViewZ.clearDataPoints();
//
//                                processorManager.setDeviceMac(deviceId.replace(":",""));
//                                processorManager.temp=2;
//                                processorManager.setDataUpdateListener(DuizhiActivity.this);
//                                processorManager.startProcessing();
//                                processorManager.setProcessingFunction(ProcessingFunction.Duizhiout);
//                            }
//                        })
//                        .setNegativeButton("取消", null)
//                        .show();
                Toast.makeText(DuizhiActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
            }
        });

    }
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getAngle();
        String flag = data.getFlag();
        System.out.println("duizhi-Flag:"+flag);
        System.out.println("duizhi-Hex: " + processedValue);
        if(flag.equals("duizhiout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
             System.out.println("dataArr: " + dataArr[0]+" "+dataArr[1]+" "+dataArr[2]);
            String da1 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
            String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
            String da3 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
//            magxDataQueue.add(Float.parseFloat(da1));
//            magyDataQueue.add(Float.parseFloat(da2));
//            magzDataQueue.add(Float.parseFloat(da3));
            waveformViewX.addDataPoint(Float.parseFloat(da1));
            waveformViewY.addDataPoint(Float.parseFloat(da2));
            waveformViewZ.addDataPoint(Float.parseFloat(da3));

//            startThreadx();
//            startThready();
//            startThreadz();
        }
        if(flag.equals("duizhiResult")){
           // Toast.makeText(DuizhiActivity.this,"测试完成，正在计算结果",Toast.LENGTH_SHORT).show();
            FeaResult duizhiRes = data.getFeaResult();
            System.out.println("duizhi"+" "+duizhiRes.predictLabel+" "+duizhiRes.predictScore);

            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isDuizhi", true);
            editor.putInt("predictLabel",duizhiRes.predictLabel);
            editor.putInt("predictScore",duizhiRes.predictScore);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < duizhiRes.displayFea.length; i++) {
                sb.append(duizhiRes.displayFea[i]);
                if (i < duizhiRes.displayFea.length - 1) sb.append(",");
            }
            editor.putString("displayFea", sb.toString());
            editor.apply();

            //停止画线程
            stopThreads();

            //跳转到结果页面
            Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
            intent.putExtra("predictLabel",duizhiRes.predictLabel);
            intent.putExtra("predictScore",duizhiRes.predictScore);
            intent.putExtra("displayFea",duizhiRes.displayFea);
            intent.putExtra("displayNames",duizhiRes.displayNames);
            startActivity(intent);

        }
    }
    /** 启动线程（只允许一个） */
    private void startThreadx() {
        if (workerThreadx != null && workerThreadx.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningx = true;
        workerThreadx = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningx) {
                runOnUiThread(() -> {
                    if(!magxDataQueue.isEmpty()) {
                        waveformViewX.addDataPoint(magxDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadx.start();
    }
    /** 启动线程（只允许一个） */
    private void startThready() {
        if (workerThready != null && workerThready.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningy = true;
        workerThready = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningy) {
                runOnUiThread(() -> {
                    if(!magyDataQueue.isEmpty()) {
                        waveformViewY.addDataPoint(magyDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThready.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadz() {
        if (workerThreadz != null && workerThreadz.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningz = true;
        workerThreadz = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningz) {
                runOnUiThread(() -> {
                    if(!magzDataQueue.isEmpty()) {
                        waveformViewZ.addDataPoint(magzDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadz.start();
    }

    /** 停止线程 */
    private void stopThreads() {
        runningx = false;
        runningy = false;
        runningz = false;
        if (workerThreadx != null) {
            workerThreadx.interrupt();
            workerThreadx = null;
        }
        if (workerThready != null) {
            workerThready.interrupt();
            workerThready = null;
        }
        if (workerThreadz != null) {
            workerThreadz.interrupt();
            workerThreadz = null;
        }
        //清空画图数据
        magzDataQueue.clear();
        magxDataQueue.clear();
        magyDataQueue.clear();
    }
//    private void getDuizhioutPlugin(String value){
//        if(startFlag==true){
//            if(saveNum<saveNumSum){
//                String resultAllout  = callPlugin(accBiasAbsFilepath,magBiasAbsFilepath,value,duizhiBias);//todo
//                saveData=saveData+saveNum+" "+resultAllout+"\n";
//                saveNum=saveNum+1;
//            }
//            if(saveNum==saveNumSum){
//                String fileName = 'duizhi-'+handDir+'-H.txt';
//                saveDuizhioutFile(fileName,saveData);
//            }
//        }
//
//    }
//    public boolean saveDuizhioutFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            duizhioutAbsFilepath=file.getAbsolutePath();
//            getDuizhiResData();
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
//    private void getDuizhiResData(){
//        String matPath =  "modelPara.mat";
//        Integer hr = 1;
//        if(handDir.equals("L")){
//            hr =1;
//        }else{
//            hr=2;
//        }
//        String DuizhiResult = callPlugin2(duizhioutAbsFilepath,matPath,hr);
//        SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
//        SharedPreferences.Editor editor = sp.edit();
//        editor.putString("DuizhiResult", DuizhiResult);
//        editor.putBoolean("isDuizhi",true);
//        editor.apply();
//        Toast.makeText(DuizhiActivity.this,"测试完成",Toast.LENGTH_SHORT).show();
//        Intent duizhiInt = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//        duizhiInt.putExtra("DuizhiResult",DuizhiResult);
//        startActivity(duizhiInt);
//    }
    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopThreads();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopThreads();
    }
}